#!/usr/bin/python
# -*- coding: utf-8 -*-

#from django.contrib.auth.middleware import RemoteUserMiddleware
from django.conf import settings
from hashlib import md5
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured

class WpAuthError(Exception):
    pass

class WpAuthMiddleware(object):

    try:
        wp_site_hash = settings.WP_SITE_ROOT
    except AttributeError:
        raise WpAuthError, 'Can not found settings [WP_SITE_ROOT]'
    else:
        wp_site_hash = md5(settings.WP_SITE_ROOT).hexdigest()

    wp_cookie_prefix = settings.WP_COOKIE_PREFIX

    # get wordpress auth cookie and logged_in cookie
    wp_auth_cookie = '%s%s' % (wp_cookie_prefix, wp_site_hash)
    wp_logged_in_cookie = '%slogged_in_%s' % (wp_cookie_prefix, wp_site_hash)

    def process_request(self, request):
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Django remote user auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the WpAuthMiddleware class.")

        try:
            wp_auth_cookie_str = request.COOKIES[self.wp_auth_cookie]
        except KeyError:
            return

        try:
            wp_logged_in_cookie_str = request.COOKIES[self.wp_logged_in_cookie]
        except KeyError:
            return

        wp_cookies_dict = {}
        wp_cookies_dict['wp_auth_cookie'] = wp_auth_cookie_str
        wp_cookies_dict['wp_logged_in_cookie'] = wp_logged_in_cookie_str

        # test user is already logged in django site ?
        if request.user.is_authenticated():

            # test current logged in user is same as current cookie
            if request.user.username == self.clean_username(wp_logged_in_cookie, request):
                return
            # current request user not same as current cookie , try to logout current user
            else:
                auth.logout(request)
                return

        # current request user not authenticated, try to check it
        else:
            # current user not logged into django site , try to auth him.
            user = auth.authenticate(wp_cookies_dict=wp_cookies_dict)
            if user:
                request.user = user
                auth.login(request, user)

    def clean_username(self, wp_cookies_dict, request):
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            username = backend.clean_username(wp_cookies_dict)
        except AttributeError:
            pass
        return username
